import pymysql
from dbutils.pooled_db import PooledDB
from loguru import logger


class DBPool:

    def __init__(self,**kwargs):
        ENGINE = kwargs.get("ENGINE",None)
        assert ENGINE in ["pymysql"],"数据库引擎不正确！"
        HOST = kwargs.get("HOST", None)
        PORT = kwargs.get("PORT", None)
        NAME = kwargs.get("NAME",None)
        USER = kwargs.get("USER",None)
        PASSWORD = kwargs.get("PASSWORD",None)
        return_dict = kwargs.get("return_dict",None)
        check_list = [x for x in [HOST,PORT,NAME,USER] if not x or x == None]
        assert not check_list,"配置信息不正确！"
        if return_dict:
            self.pool = PooledDB(creator=pymysql,host=HOST,port=int(PORT),user=USER,password=PASSWORD,database=NAME,cursorclass=pymysql.cursors.DictCursor)
        else:
            self.pool = PooledDB(creator=pymysql, host=HOST, port=int(PORT), user=USER, password=PASSWORD, database=NAME)
        self.conn = self.pool.connection()
        self.cursor = self.conn.cursor()
        logger.debug("数据库连接成功！")

    def create_conn_cursor(self):
        conn = self.pool.connection()
        cursor = conn.cursor()
        return conn, cursor

    def close_cursor(self,):
        self.cursor.close()
        self.conn.close()


    # 查询1个满足条件的数据
    def fetch_one(self, sql,query=None):
        try:
            conn, cursor = self.create_conn_cursor()
            cursor.execute(sql,query)
            obj = cursor.fetchone()
            cursor.close()
            conn.close()
            # self.cursor.execute(sql)
            # obj = self.cursor.fetchone()
            return True,obj
        except:
            return False,""

    # 查询满足条件的所有数据
    def fetch_all(self, sql,query=None):
        try:
            conn, cursor = self.create_conn_cursor()
            cursor.execute(sql,query)
            obj = cursor.fetchall()
            cursor.close()
            conn.close()
            # self.cursor.execute(sql)
            # obj = self.cursor.fetchall()
            return True,obj
        except Exception as e:
            logger.exception(e)
            return False,[]

    # 执行单条处理
    def exe_sql(self,sql,query=None):
        try:
            conn, cursor = self.create_conn_cursor()
            cursor.execute(sql,query)
            conn.commit()
            cursor.close()
            conn.close()
            # self.cursor.execute(sql)
            # self.conn.commit()
            return True
        except Exception as e:
            logger.error(f"错误：{e},执行sql:{sql}失败！")
            try:
                conn.rollback()
                conn.close()
            except:
                pass
            return False

    # 执行多条任务处理
    def exe_many_sql(self,sql,data):
        try:

            conn, cursor = self.create_conn_cursor()
            num = cursor.executemany(sql,data)
            conn.commit()
            cursor.close()
            conn.close()

            return True,num
        except Exception as e:
            logger.error(f"错误：{e},执行sql:{sql}失败！")
            try:
                conn.rollback()
                conn.close()
            except:
                pass
            return False,0

    def __del__(self):
        try:
            logger.debug("关闭@！")
            self.cursor.close()
            self.conn.close()
        except Exception as e:
            logger.warning(f"数据库连接关闭异常：{e}")

if __name__ == '__main__':
    pass

